const TRANSPARENT_RAIL_MAP = false
const WATER_MAP_OFFSET = [0, 3]
const data = window.希服轨交线网图 ??= { railMap: null, waterMap: null }
SoulLS.$file.onchange = async () => {
  let svgCode = await SoulLS.file.text()
  if (svgCode.slice(0, 100).includes("Illustrator")) {
    data.waterMap = svgCode
    SoulLS.out = new Date().toLocaleTimeString() + " 成功加载水体图\n" + SoulLS.out
  } else {
    data.railMap = svgCode
    SoulLS.out = new Date().toLocaleTimeString() + " 成功加载线路图\n" + SoulLS.out
  }
}
if (!(data.railMap && (TRANSPARENT_RAIL_MAP || data.waterMap))) return "请用“选择文件”加载线路图和水体图后点击“eval code”\n"
SoulLS.out = ""
let [topLeft, left, top] = data.railMap.match(/<g id="misc_node_CORNTOPLEF"[^>]+?translate\((-?[\d.]+), (-?[\d.]+)\)/) ?? []
let [bottomRight, right, bottom] = data.railMap.match(/<g id="misc_node_CORNBOTRIG"[^>]+?translate\((-?[\d.]+), (-?[\d.]+)\)/) ?? []
;[left, top, right, bottom] = [left, top, right, bottom].map(Number)
if (!topLeft) return "未找到 misc_node_CORNTOPLEF"
if (!bottomRight) return "未找到 misc_node_CORNBOTRIG"
const waterCode = TRANSPARENT_RAIL_MAP ? "" : data.waterMap
  .replace(/.*?(?=<svg\b)/s, "")
  .replace(/viewBox="-?\d+(?:\.\d*)? -?\d+(?:\.\d*)? (-?\d+(?:\.\d*)?) (-?\d+(?:\.\d*)?)"/, '$& width="$1" height="$2"')
const railCode = data.railMap
  .replaceAll(
    "Arial",
    "XegoeUINewExt, Segoe UI"
  )
  .replace(
    /position: fixed; top: 40px; left: 40px; user-select: none; touch-action: none/,
    ""
  )
  .replace(/(?<=<svg\b[^>]+>)/, () => `<g transform="translate(${left + WATER_MAP_OFFSET[0]} ${top + WATER_MAP_OFFSET[1]})">${waterCode}</g>`)
  .replace(/(?=<\/style>)/, ".rmp-name-outline { stroke-width: 1.5px } #rmp_info { visibility: hidden } text { white-space: pre }")
  .replace(/^(.*?)height=".+?"/, `$1height="${bottom - top}"`)
  .replace(/^(.*?)width=".+?"/, `$1width="${right - left}"`)
  .replace(/^(.*?)viewBox=".+?"/, `$1viewBox="${left} ${top} ${right - left} ${bottom - top}"`)
const img = new Image()
await new Promise((resolve, reject) => {
  img.onload = resolve
  img.onerror = reject
  img.src = "data:image/svg+xml," + encodeURIComponent(railCode)
})
const canvas = new OffscreenCanvas(img.width * 3, img.height * 3)
const ctx = canvas.getContext("2d")
if (!TRANSPARENT_RAIL_MAP) {
  ctx.fillStyle = "white"
  ctx.fillRect(0, 0, canvas.width, canvas.height)
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
const link = document.createElement("a")
link.href = URL.createObjectURL(await canvas.convertToBlob())
link.download = SoulLS.file.name.replace(/\.[\w-]+$/, "") + ".png"
link.click()
